package servlet;


import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/deleteBlog")
public class DeleteServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端传来的 blogId
        Integer blogId = Integer.parseInt(req.getParameter("blogId"));

        // 数据库连接相关
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            // 获取数据库连接
            connection = DBUtil.getConnection();

            // SQL 删除语句
            String sql = "DELETE FROM blog WHERE blogId = ?";

            // 创建 PreparedStatement
            statement = connection.prepareStatement(sql);

            // 设置参数
            statement.setInt(1, blogId);

            // 执行删除操作
            int rowsAffected = statement.executeUpdate();

            // 设置响应类型为 JSON
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");

            // 判断删除是否成功，返回相应的 JSON 数据
            if (rowsAffected > 0) {
                // 删除成功
                resp.getWriter().write("{\"success\": true, \"message\": \"博客删除成功！\"}");
            } else {
                // 删除失败
                resp.getWriter().write("{\"success\": false, \"message\": \"删除失败，未找到该博客！\"}");
            }
        } catch (SQLException e) {
            // 捕获 SQL 异常，返回错误信息
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 服务器内部错误
            resp.getWriter().write("{\"success\": false, \"message\": \"服务器错误，请稍后再试！\"}");
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
